import {Ajax} from "../ajax";

class PageStore {

    constructor() {
        this.limit = 20;
        this.status = {
            pageNum: 1,
            isEnd: false,
            isLoading: false,
            isEmpty: false,
            totalPage: 0
        };
        this.data = [];
        this.mode = 'get';
        this.useTotalPage = true;
        this.api = '';
    }

    /**
     * 初始化
     */
    clear() {
        this.data = [];
        Object.assign(this.status, {
            pageNum: 1,
            isEnd: false,
            isLoading: false,
            isEmpty: false,
            totalPage: 0
        });
        this.onChange(this.data, this.status);
    }

    /**
     * 获取分页数据
     * @param pageNum
     * @param opt
     * @returns {Promise<T>}
     */
    load(api, paras) {
        if (this.status.isLoading) {
            return Promise.reject('数据加载中');
        }
        if (this.status.isEnd) {
            return Promise.reject('没有更多数据了');
        }
        const data = Object.assign(this.buildPara(), paras || {});
        this.status.isLoading = true;
        this.onChange(this.data, this.status);
        return Ajax[this.mode](api || this.api, data, {
            paras: data
        }).then(result => {
            result = this.filter(result);
            if (this.useTotalPage) {
                this.status.totalPage = Math.ceil(result.total / this.limit);
            }

            this.status.isEmpty = this.status.pageNum === 1 && result.data.length === 0;
            this.status.pageNum++;
            this.status.isLoading = false;
            this.append(result.data);
            return result.data;
        }).catch(() => {
            this.status.isLoading = false;
        });
    }

    /**
     * 生成分页参数
     * @returns {{offset: number, limit: number}}
     */
    buildPara() {
        return {
            limit: this.limit,
            offset: (this.status.pageNum - 1) * this.limit
        }
    }

    /**
     * 调用了load方法，请求到了接口数据后触发
     * 子类可重写该方法
     * 返回的res必须为{data:[],total:999}，其中total为可选
     * @param res
     * @returns {*}
     */
    filter(res) {
        return res;
    }

    /**
     * 加载新的分页数据
     * @param list
     */
    append(list) {
        if (!Array.isArray(list)) {
            return;
        }
        if (list.length < this.limit) {
            this.status.isEnd = true;
        }
        if (list.length === 0) {
            if (this.status.pageNum === 1) {
                this.status.isEmpty = true;
            }
        } else {
            this.data = [...this.data, ...list];
        }
        this.onChange(this.data, this.status);
    }

    /**
     * 数据变化时触发
     * @param data
     * @param status
     */
    onChange(data, status) {

    }
}

export {
    PageStore
}

export default PageStore;
